package com.android.advertising;

import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class ArticleDetailActivity extends ActionBarActivity {
	private ArticleDatabase database;
	private static final String TAG = "ArticleDetailActivity";
	ActionBar actionBar;
	private ProgressDialog progressBar;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		if (!MainService.isReady()) {
			Intent intent = new Intent(this, MainService.class);
			startService(intent);
		} else {
			MainService.getInstance().removeNotification();
		}
		setContentView(R.layout.article_details);
		actionBar = getSupportActionBar();
		actionBar.setDisplayUseLogoEnabled(true);
		setSupportProgressBarIndeterminateVisibility(false);
		Bundle extras = getIntent().getExtras();
		long id = extras.getLong(Constants.ARTICLES_ID);
		database = ArticleDatabase.getInstance(getApplicationContext());
		Article article = database.findArticleById((int) id);
		database.setArticleIsRead((int) article.getId());
		if (article.getLink() != null) {
			WebView webView = (WebView) findViewById(R.id.webView);
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			WebSettings websetting = webView.getSettings();
			websetting.setDefaultTextEncodingName("utf-8");
			// final AlertDialog alertDialog = new AlertDialog.Builder(this)
			// .create();
			// progressBar = ProgressDialog.show(this,
			// getString(R.string.app_name), "Loading...");

			getArticleContent(getApplicationContext(), article, webView);
			// webView.setWebViewClient(new WebViewClient() {
			// public boolean shouldOverrideUrlLoading(WebView view, String url)
			// {
			// Log.i(TAG, "Processing webview url click...");
			// view.loadUrl(url);
			// // view.loadData(url, "text/html; charset=utf-8", null);
			// return true;
			// }
			//
			// public void onPageFinished(WebView view, String url) {
			// Log.i(TAG, "Finished loading URL: " + url);
			// if (progressBar.isShowing()) {
			// progressBar.dismiss();
			// }
			// }
			//
			// public void onReceivedError(WebView view, int errorCode,
			// String description, String failingUrl) {
			// Log.e(TAG, "Error: " + description);
			// Toast.makeText(getApplicationContext(),
			// "Oh no! " + description, Toast.LENGTH_SHORT).show();
			// alertDialog.setTitle("Error");
			// alertDialog.setMessage(description);
			// alertDialog.setButton("OK",
			// new DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog,
			// int which) {
			// return;
			// }
			// });
			// alertDialog.show();
			// }
			// });
			// webView.loadUrl(article.getLink());

			// webView.loadDataWithBaseURL("fake://not/needed", html,
			// "text/html", "utf-8", "");

		}
	}

	private void getArticleContent(Context ctx, Article article,
			final WebView webView) {
		setSupportProgressBarIndeterminateVisibility(true);
		StringRequest postRequest = new StringRequest(Request.Method.GET,
				article.getLink(), new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						// response
						setSupportProgressBarIndeterminateVisibility(false);
						Log.d(TAG, response);
						// response = Uri.encode(response);
						response = "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-16le\"><body>"
								+ response + "</body></html>";
						webView.loadDataWithBaseURL("fake://not/needed",
								response, "text/html", "utf-8", "");
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// error
						setSupportProgressBarIndeterminateVisibility(false);
						Log.d(TAG, error.toString());
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				Map<String, String> params = new HashMap<String, String>();
				return params;
			}
		};
		RequestQueue queue = Volley.newRequestQueue(ctx);
		queue.add(postRequest);
	}

}
